import XLSX from "xlsx"

export const SaveExcel = ({ sheetArr, name }) => {
  let myswith = {
    jsonType(data) {
      return XLSX.utils.json_to_sheet(data);
    },
    aoaType(data) {
      return XLSX.utils.aoa_to_sheet(data);
    }
  }
  let workbook = XLSX.utils.book_new();
  let flag = true;
  for (let item of sheetArr) {
    if (typeof item.data.length == "undefined" || typeof item.data[0] == "undefined") {
      flag = false;
      break;
    }
    let type = "aoaType";
    if (typeof item.data[0].length == "undefined") {
      type = "jsonType";
    }
    XLSX.utils.book_append_sheet(workbook, myswith[type](item.data), item.sheetName);
  }
  if (!flag) {
    return false;
  }
  XLSX.writeFile(workbook, `${name}.xlsx`);
  console.log("保存成功")
  return true;
}
export const CreateExcelData = ({
  arr,
  mapping = null,
  isOrder = true
}) => {
  return isOrder ?
    mapping == null ?
      arr.map((item, index) => [index + 1, ...Object.values(item)]) : [
        Object.values({
          "orderId": "序号",
          ...mapping
        }),
        ...arr.map((item, index) => Object.keys({
          "orderId": "序号",
          ...mapping
        }).map(oi => oi == "orderId" ? index + 1 : item[oi]))
      ] :
    mapping == null ?
      arr.map(item => [...Object.values(item)]) : [
        Object.values(mapping),
        ...arr.map(item => Object.keys(mapping).map(oi => item[oi]))
      ];
}
export const SaveTable = ({ arr, mapping, isOrder=true }) => {
  SaveExcel({
    sheetArr: [
      {
        sheetName: `data`,
        data: CreateExcelData({
          arr,
          isOrder,
          mapping,
        })
      },
    ],
    name: "data",
  })
}
